package com.filesystem.file.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.filesystem.file.entity.Files;
import com.filesystem.file.mapper.FileMapper;
import com.filesystem.file.service.IFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.filesystem.utils.ResponseCode;
import com.filesystem.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.StandardCopyOption;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author JayZhou
 * @since 2021-06-10
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, Files> implements IFileService {

    @Autowired
    private FileMapper fileMapper;


    /**
     *
     */
    @Value("${file.save-path}")
    private String savePath;



    @Override
    public List<Files> userListFile(String  username ,int page , int limit ) {
        return fileMapper.userListFile(username,page ,limit);
    }


    /**
     *  上传服务
     * @param file 上传的文件
     * @return 返回json
     */
    @Override
    public Result upLoadFiles(MultipartFile file , String filetitle ,int filetype) {
        long MAX_SIZE=2097152L;
        String fileName= file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)){
            return new Result(ResponseCode.FILE_NAME_EMPTY.getCode(),ResponseCode.FILE_NAME_EMPTY.getMsg(),null);
        }
        if (file.getSize()>MAX_SIZE){
            return new Result(ResponseCode.FILE_MAX_SIZE.getCode(),ResponseCode.FILE_MAX_SIZE.getMsg(),null);
        }

        //获取文件
        //InputStream inputStream = file.getInputStream();
        //文件后缀
        String suffixName = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".")) : null;
        //
        String  filename = UUID.randomUUID() +suffixName;


        String newName = System.currentTimeMillis() + suffixName;
        File newFile=new File(savePath,newName);
        if (!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        try {
            //文件写入
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }



        //获取当前登录的账号
        Subject subject = SecurityUtils.getSubject();
        String username = subject.getPrincipal().toString();
        Files files =new Files(fileName,filetitle,filetype,username,suffixName,new Date());
        System.out.println("打印执行--------------");
        System.out.println(files);
        System.out.println("打印结束--------------");
        fileMapper.insertFile(files);
        return new Result(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getMsg(),"数据上传成功");
    }

    @Override
    public Files getFileById(String id) {
        return fileMapper.selectFileById(id);
    }

    @Override
    public InputStream getFileInputStream(Files files) {
        File file=new File(files.getFilepath());
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  查询分页数据
     * @param page 页数
     * @param limit 展示条数
     * @param filename 文件名
     * @param username 用户名
     * @return 返回查询结果
     */
    @Override
    public Page<Files> select(int page, int limit,String filename, String username) {
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        Page<Files> filesPage = new Page<>(page,limit);
        queryWrapper.like("username",username)
                    .like("filename",filename);
        if (filename == null && username == null){
            return  fileMapper.selectPage(filesPage, null);
        }
        return fileMapper.selectPage(filesPage, queryWrapper);
    }

    /**
     * 查询自己上传的文件
     * @param page 页数
     * @param limit 条数
     * @param username 用户名
     * @return 返回该用户上传的数据
     */
    @Override
    public Page<Files> selectuser(int page, int limit, String username) {
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        Page<Files> filesPage = new Page<>(page,limit);
        queryWrapper.eq("username",username);
        return fileMapper.selectPage(filesPage,queryWrapper);
    }


}
